package com.jinzhi.sysxn.controller;



import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sysxn.domain.UserExportRequest;
import com.jinzhi.sysxn.service.UserXnService;
import com.jinzhi.sysxn.vo.UserXnExportVO;
import com.jinzhi.sysxn.vo.UserXnImportVO;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author hss
 * @version 1.0
 * @date 2023/12/5 15:28
 */
@RequestMapping("/sysxn/user")
@Controller
public class UserXnController extends BaseController {
    private String prefix = "sysxn/user";

    @Autowired
    UserXnService userXnService;

    @Log("查询用户列表")
    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("sysxn:user:list")
    public Result<Page<UserDO>> list(UserDO userDTO) {
        Page<UserDO> page = userXnService.selectPage(userDTO, getPage(UserDO.class));
        return Result.ok(page);
    }

    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    @Transactional
    @RequiresPermissions("sysxn:user:remove")
    Result<String> remove(Long id) {
        return userXnService.remove(id);
    }

    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("管理员提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    @RequiresPermissions("sysxn:user:adminResetPwd")
    Result<String> adminResetPwd(UserDO user) {
        userXnService.adminResetPwd(user);
        return Result.ok();

    }

    /**
     * 管理员查看用户详情
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/info/{id}")
    String info(@PathVariable("id") Long id, Model model) {
        UserDO userDO = userXnService.selectById(id);
        model.addAttribute("user", userDO);
//        return prefix + "/info";
        return "jzweb/userManagement/info";
    }

    @Log("管理员添加用户")
    @GetMapping("/add")
    @RequiresPermissions("sysxn:user:add")
    String add(Model model) {
        return "jzweb/userManagement/add";
    }

    @Log("管理员保存用户")
    @PostMapping("/save")
    @ResponseBody
    @RequiresPermissions("sysxn:user:save")
    Result<String> save(@RequestBody UserDO user) {
        return userXnService.addUser(user);
    }

    @Log("管理员编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDO userDO = userXnService.selectById(id);
        model.addAttribute("user", userDO);
        return "jzweb/userManagement/edit";
    }

    /**
     * 通过id获取用户详情
     *
     * @param id
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    Result<UserDO> select(Long id) {
        UserDO userDO = userXnService.selectById(id);
        return Result.ok(userDO);
    }

    @Log("管理员修改用户")
    @PostMapping("/update")
    @ResponseBody
    Result<String> update(@RequestBody UserDO user) {
        return userXnService.update(user);
    }

//    @Log("修改学号/工号")
//    @PostMapping("/updateNumber")
//    @ResponseBody
//    Result<String> updateNumber(UserDO user) {
//        userXnService.updateNumber(user);
//        return Result.ok();
//    }

//    @Log("修改手机号")
//    @PostMapping("/updateMobile")
//    @ResponseBody
//    Result<String> updateMobile(UserDO user) {
//        userXnService.updateMobile(user);
//        return Result.ok();
//    }

    /**
     * 用户导出信息
     *
     * @param response
     */
    @GetMapping("/downloadUserXn")
    @ResponseBody
    public void downloadUserXn(HttpServletResponse response,UserExportRequest userExportRequest) {
        List<UserXnExportVO> list1 = userXnService.downloadUserXn(userExportRequest);
        //导出操作
        EasyPoiUtil.exportExcel(list1, "用户信息", "用户信息", UserXnExportVO.class, "用户信息", response);
    }

    /**
     * 用户信息导入
     *
     * @param file excel文件
     */
    @Log("用户信息导入")
    @PostMapping("/import")
    @ResponseBody
    @Transactional
    public Result<?> importExcel(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
        return userXnService.importExcel(file, this.getUserId());
    }


    /**
     * 下载导入模板
     *
     * @param response
     */
    @RequestMapping("/downloadImportTemplate")
    @ResponseBody
    public void downloadImportTemplate(HttpServletResponse response) {
        List<UserXnImportVO> list = new LinkedList<>();
        //导出操作
        EasyPoiUtil.exportExcel(list, "用户信息", "用户信息", UserXnImportVO.class, "用户信息", response);
    }

    /**
     * 导出错误信息
     *
     * @param request
     * @param response
     * @throws Exception
     * @author kl
     */
    @Log("导出错误信息")
    @GetMapping("/importComError")
    @ResponseBody
    @Transactional
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户导入错误信息", "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        String jsonArray = EhCacheUtil.get("userImport" + this.getUserId()).toString();
        JSONArray arrayList = JSONArray.parseArray(jsonArray);
        //转换为目标对象list
        List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
        workbook.write(response.getOutputStream());
    }

    @ApiOperation(value = "用户台管理页面入口", notes = "用户后台管理页面入口")
    @ApiImplicitParams({
    })
    @ApiResponses({@ApiResponse(code = 0, message = "操作成功"), @ApiResponse(code = 500, message = "服务器内部异常")})
    @GetMapping("/index")
    String getList(Model model) {
        List<Map> mylist = getRolePageButton("/sysxn/user/index");
        String authority = "";
        for (Map map : mylist) {
            authority += map.get("name") + ",";
        }
        authority = authority.length() > 0 ? authority.substring(0, authority.length() - 1) : "";
        model.addAttribute("authorityButtonAdd", authority.contains("新增"));
        model.addAttribute("authorityButtonEdit", authority.contains("修改"));
        model.addAttribute("authorityButtonInquire", authority.contains("查询"));
        model.addAttribute("authorityButtonDelete", authority.contains("删除"));
        model.addAttribute("authorityButtonResetPSW", authority.contains("重置"));
        model.addAttribute("authorityButtonLookInfor", authority.contains("详情"));
        model.addAttribute("authorityButtonImportData", authority.contains("导入"));
        model.addAttribute("authorityButtonExportData", authority.contains("导出"));
        model.addAttribute("authorityButtonDownload", authority.contains("下载"));


        model.addAttribute("authority", authority.split(","));
        return "jzweb/userManagement/index";
    }


}
